<template>
  <div class="order-management">
    <!-- 基础搜索 -->
    <el-header class="header">
      <el-menu class="top-nav-menu" mode="horizontal">
        <el-menu-item index="2" @click="shouye">首页</el-menu-item>
        <el-menu-item index="xianhua" @click="xianhua">鲜花大厅</el-menu-item>
        <!-- 购物车图标 -->
        <el-menu-item index="6" class="cart-menu-item" @click="showCart">
          <el-tooltip class="item" effect="dark" content="购物车" placement="bottom">
            <i class="el-icon-shopping-cart-2"></i>
          </el-tooltip>
        </el-menu-item>
      </el-menu>
    </el-header>

    <!-- 条件搜索 -->
    <el-form inline class="search-form">
      <el-form-item label="用户ID">
        <el-input v-model="searchUserId" placeholder="用户ID"></el-input>
      </el-form-item>
      <el-form-item label="金额范围">
        <el-col :span="11">
          <el-form-item prop="minPrice">
            <el-input type="number" v-model="minPrice" placeholder="最低金额"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item prop="maxPrice">
            <el-input type="number" v-model="maxPrice" placeholder="最高金额"></el-input>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="searchStatus" placeholder="请选择">
          <el-option label="未支付" value="1"></el-option>
          <el-option label="已支付" value="2"></el-option>
          <el-option label="待收货" value="3"></el-option>
          <el-option label="已收货" value="4"></el-option>
          <el-option label="已完成" value="5"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">高级搜索</el-button>
        <el-button @click="clearSearch">清空搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 批量操作按钮 -->
    <div style="text-align: left">
      <el-button type="danger" @click="deleteSelectedOrders" :disabled="selectedOrderIds.length === 0">删除选中订单
      </el-button>
    </div>

    <el-table :data="pagedOrders" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="oid" label="订单编号"></el-table-column>
      <el-table-column label="商品" width="120">
        <template slot-scope="scope">
          <el-avatar :size="60" :src="scope.row.flower.fsrc" shape="square">
            <img src="../imgs/error.png"/>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="flower.fname" label="商品名称"></el-table-column>
      <el-table-column prop="oprice" label="订单价格"></el-table-column>
      <el-table-column prop="quantity" label="数量"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="订单状态">
        <template slot-scope="scope">
          <el-button
              v-if="scope.row.state === 1"
              type="info"
              @click="updateStatus(scope.row, 2)"
          >未支付</el-button>
          <el-button
              v-else-if="scope.row.state === 2"
              type="success"
              disabled
          >已支付</el-button>
          <el-button
              v-if="scope.row.state === 3"
              type="info"
              disabled
          >待发货</el-button>
          <el-button
              v-else-if="scope.row.state === 4"
              type="success"
              @click="updateStatus(scope.row, 5)"
          >待收货</el-button>
          <el-button
              v-if="scope.row.state === 5"
              type="success"
              @click="pinglun(scope.row, 8)"
          >待评论</el-button>
          <el-button
              v-if="scope.row.state === 0"
              type="success"
              @click="isUpdate(scope.row)"
          >申请退款</el-button>
          <el-button
              v-if="scope.row.state === 6"
              type="success"
              disabled
          >已退款</el-button>
          <el-button
              v-if="scope.row.state === 7"
              type="success"
              disabled
          >退款申请拒绝了</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="danger" @click="deleteOrder(scope.row.oid)">删除</el-button>
            <el-button
                v-if="scope.row.state >= 2 && scope.row.state <= 5"
                type="success"
                @click="shenqing"
            >申请退款</el-button>


          <el-dialog
              title="退款申请"
              :visible.sync="refundDialogVisible"
              width="30%"
          >
            <el-form>
              <el-form-item label="退款理由">
                <el-input
                    type="textarea"
                    v-model="order.comment"
                    placeholder="请输入退款理由"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
      <el-button @click="refundDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitRefund">提交申请</el-button>
    </span>
          </el-dialog>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredOrders.length"
    >
    </el-pagination>
  </div>
</template>

<script>
import {Table, TableColumn, Input, Button, Pagination, Form, FormItem, Select, Option, Col} from 'element-ui';
import request from "@/utils/request";
import {v4 as UUID} from "uuid";


export default {
  components: {
    [Table.name]: Table,
    [TableColumn.name]: TableColumn,
    [Input.name]: Input,
    [Button.name]: Button,
    [Pagination.name]: Pagination,
    [Form.name]: Form,
    [FormItem.name]: FormItem,
    [Select.name]: Select,
    [Option.name]: Option,
    [Col.name]: Col
  },
  data() {
    return {
      refundDialogVisible: false, // 控制退款申请模态框的显示
      users: [], // 用于存储用户名
      user: { // 存储用户信息
        username: '',
        src: ''
      },
      Shops: {
        sid: '',
        sname: '',
        spassword: '',
        siphone: '',
        src: ''
      },
      orders: [],
      searchQuery: '',
      searchUserId: '',
      minPrice: null,
      maxPrice: null,
      searchStatus: null,
      currentPage: 1,
      pageSize: 3,
      selectedOrderIds: [], // 用于存储选中的订单ID
      order: {
        oid : '',
        user: {
          id: '',
          username: '',
          password: '',
          iphone: '',
          src: ''
        },
        shops: {
          sid: '',
          sname: '',
          spassword: '',
          siphone: '',
          src: ''
        },
        flower: {
          fid: '',
          fname: '',
          faddress: '',
          flangure: '',
          fsrc: '',
          price: '',
          number: '',
          types: {
            tid: '',
            tname: '',
            sid: ''
          },
          shops:{
            sid: '',
            sname: '',
            spassword: '',
            siphone: '',
            src: ''
          }
        },
        oprice: '',
        createTime: '',
        state: 1,
        address: '',
        quantity:'',
        appraise: '',
        points: '',
        comment: ''
      },
      userForm: {
        id: 0,
        username: '',
        password: '',
        iphone: '',
        src: '',
      },
      uid: 0
    }
  },
  computed: {
    filteredOrders() {
      let result = this.orders;
      if (this.searchQuery) {
        result = result.filter(order => order.customerName.toLowerCase().includes(this.searchQuery.toLowerCase()));
      }
      if (this.searchUserId) {
        result = result.filter(order => order.id === parseInt(this.searchUserId));
      }
      if (this.minPrice !== null) {
        result = result.filter(order => order.price >= this.minPrice);
      }
      if (this.maxPrice !== null) {
        result = result.filter(order => order.price <= this.maxPrice);
      }
      if (this.searchStatus) {
        result = result.filter(order => order.status === parseInt(this.searchStatus));
      }
      return result;
    },
    pagedOrders() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredOrders.slice(start, end);
    }
  },
  methods: {
    // 拿到订单所有数据
    getOrders() {
      // 假设 this.orders 已经从后端获取到了数据
      this.cartList.forEach((creat) => {
        const order = {
          user: {
            id: creat.user.id,
            username: creat.user.username,
            password: creat.user.password,
            iphone: creat.user.iphone,
            src: creat.user.src,
          },
          shops: {
            sid: creat.flower.shops.sid,
            sname: creat.flower.shops.sname,
            spassword: creat.flower.shops.spassword,
            siphone: creat.flower.shops.siphone,
            src: creat.flower.shops.src,
          },
          flower: {
            fid: creat.flower.fid,
            fname: creat.flower.fname,
            faddress: creat.flower.faddress,
            flangure: creat.flower.flangure,
            fsrc: creat.flower.fsrc,
            price: creat.flower.price,
            number: creat.flower.number,
          },
          state: 1, // 状态
          address: '', // 初始地址为空
          quantity: creat.num, // 数量
          oprice: creat.flower.price * creat.num, // 订单总价
        };
        this.currentOrder.push(order);
      });

      //   // 显示订单数据
      //   this.currentOrder.forEach((order, index) => {
      //     alert(`订单 ${index + 1}:
      // 用户id: ${order.user.id}
      // 商家id: ${order.shops.sid}
      // 商品id: ${order.flower.fid}
      // 状态: ${order.state}
      // 数量: ${order.quantity}
      // 订单总价: ${order.oprice}`);
      //   });
    },
    submitRefund() {
      // 假设你已经在data中定义了order对象，并且它有一个comment属性
      this.order.comment = this.order.comment || ''; // 确保comment属性存在并有初始值

      // 这里你可以添加逻辑来获取用户输入的退款理由
      // 例如，如果你有一个表单输入绑定到这个值：this.order.comment = this退款理由输入绑定的值;

      // 调用添加订单的方法（这通常会在某个API服务中处理）
      this.addOrder(this.order).then(response => {
        // 处理响应
        if (response.data.code === 200) {
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          // 可能需要清空表单或关闭对话框
          this.refundDialogVisible = false;
          this.order.comment = ''; // 清空理由
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg
          });
        }
      }).catch(error => {
        // 处理错误
        console.error('添加订单失败', error);
        this.$message.error('添加订单失败');
      });
    },
// ------------------下单------------------------
    addOrder() {
      this.getOrders(); // 确保 getOrder 被调用
      this.getSelectedIds(); // 更新并打印已选择的商品ID
      this.orderItems = this.cartList.filter((item) => item.selected); // 获取选中的商品
      if (this.orderItems.length > 0) {
        this.currentOrder = []; // 清空当前订单
        // 遍历选中的商品项，为每个商品创建一个新的订单对象
        this.orderItems.forEach((item) => {
          const newUUID = UUID(); // 为每个订单生成新的 UUID
          const newOrder = {
            'oid': newUUID, // 订单ID
            user: {
              'id': item.user.id, // 用户ID
            },
            shops: {
              'sid': item.flower.shops.sid, // 商家ID
            },
            flower: {
              'fid': item.flower.fid, // 商品ID
            },
            'items': [item], // 订单中的商品项
            'address': '', // 初始地址为空
            'quantity': item.num, // 设置数量
            'oprice': (item.flower.price * item.num).toFixed(2), // 计算小计
            'state': 1, // 初始状态设置为 'pending'
            'createTime': new Date().toISOString().slice(0, 19).replace('T', ' '), // 创建时间
          };
          this.currentOrder.push(newOrder) // 将每个商品作为一个单独的订单添加到当前订单中
        });
        this.orderModalVisible = true; // 显示模态框
      } else {
        alert('请先选择商品');
      }
    },

    // 退款
    shenqing(){
      this.refundDialogVisible = true
      console.log('申请退款');
    },

    shouye() {
      this.$router.push('/')
    },
    xianhua() {
      this.$router.push('/xianHua')
    },
    showCart() {
      this.$router.push('/goShop')
    },

    //根据用户名查询
    selectName() {
      request({
        method: 'post',
        url: 'http://localhost:9091/user/selectOne',
      }).then(res => {
        if (res.data && res.data.data && res.data.data.src) {
          this.users = [res.data.data];// 将对象包装在数组中
          this.userForm = res.data.data;
          this.src = res.data.data.src;
          this.uid = res.data.data.id
          this.originalPassword = res.data.data.password; // 设置原始密码
          console.log(this.uid)
          this.getOrder(); // 调用 getOrder 方法获取订单数据
        } else {
          console.error('头像数据获取失败');
        }
      })
    },

    // 获取订单数据
    getOrder() {
      if (this.username === null || this.username === '') {
        this.$message.error('请先登录');
        return;
      } else {
        request({
          method: 'get',
          url: 'http://localhost:9091/Order/getOrder',
        }).then(response => {
          if (response.data.code === 200) {
            this.orders = response.data.data; // 更新购物车列表
            console.log(this.orders)
          } else {
            this.$message.error(response.data.message);
          }
        })
      }
    },

    deleteOrder(orderId) {
      this.order.oid = orderId;
      this.order.shops.sname = this.Shops.sname
      request({
        url: 'http://localhost:9091/Order/deleteOrder',
        method: 'post',
        data: this.order
      }).then(response => {
        if (response.data.code === 200) {
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          this.getOrder()
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg
          });
        }
      })
    },
    updateStatus(order, newStatus) {
      let ordersss = {
        oid: order.oid,
        state: newStatus,
        shops: {
          sname: order.shops.sname
        }
      };
      request({
        url: 'http://localhost:9091/Order/updateOrder',
        method: 'post',
        data: ordersss
      }).then(response => {
        if (response.data.code === 200) {
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          this.getOrder()
        } else {
          this.$message({
            type: 'error',
            message: response.data.msg
          });
        }
      })
    },

    handleSearch() {
      // 重置当前页码
      this.currentPage = 1;
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },

    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },

    clearSearch() {
      this.searchQuery = '';
      this.searchUserId = '';
      this.minPrice = null;
      this.maxPrice = null;
      this.searchStatus = null;
      this.currentPage = 1; // 重置到第一页
      this.selectedOrderIds = []; // 清空已选
    },

    handleSelectionChange(selection) {
      this.selectedOrderIds = []
      for (let i = 0; i < selection.length; i++) {
        this.selectedOrderIds.push(selection[i].oid);
      }
      console.log(this.selectedOrderIds)
    },

    deleteSelectedOrders() {
      if (this.selectedOrderIds.length === 0) {
        this.$message({
          type: 'warning',
          message: '请先选择要删除的订单'
        });
        return;
      }
      request({
        url: 'http://localhost:9091/Order/deleteMoreOrder',
        method: 'post',
        data: this.selectedOrderIds
      }).then(response => {
        this.$message({
          type: 'success',
          message: '删除成功',
          response
        });
        this.getOrder();  // 重新获取订单数据
        this.selectedOrderIds = [];  // 清空已选订单ID数组
        this.getOrder();  // 重新获取订单数据
      });
    },

    getCookie(name) {
      let nameEQ = name + "=";
      let ca = document.cookie.split(';');
      for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
      }
      return '';
    },

    getToken() {
      request({
        method: 'post',
        url: 'http://localhost:9091/user/getTook',
      }).then(res => {
        if (res.data.code === 200) {
          console.log(res)
          if (res.data.data != null) {
            this.username = res.data.data.username
            this.users = res.data.data;
            this.users.username = this.username;
            this.src = res.data.data.src
            this.selectName();
          }
        }
      })
    },
  },

  created() {
    this.getToken()

  }
}
</script>

<style>
.order-management {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.line {
  text-align: center;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>